package com.jt.permission.service;

import com.jt.base.BaseService;
import com.jt.permission.mapper.RoleMapper;
import com.jt.permission.mapper.RoleMenuMapper;
import com.jt.permission.model.Role;
import com.jt.permission.model.RoleMenu;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class RoleService extends BaseService<Long, Role> {

  @Resource
  private RoleMenuMapper sysRoleMenuMapper;

    public List<Role> queryAllRolles(Long userId){
        return ((RoleMapper)mapper).queryAllRolles(userId);
    }

  public Role saveOrUpdateRoleMenu(Role sysRole, List<Long> menuIdList) {
    boolean isNew = true;
    if(sysRole.getRoleId()!=null){
      Role sysRoleDb =  selectByKey(sysRole.getRoleId());
      if(sysRoleDb!=null){//已经存在数据库的对象
        isNew = false;
        Example example = new Example(RoleMenu.class);
        example.createCriteria().andEqualTo("roleId",sysRole.getRoleId());
        sysRoleMenuMapper.deleteByExample(example);//删除已经存在的角色菜单关系
        sysRoleDb.setRemark(sysRole.getRemark());
        sysRoleDb.setRoleName(sysRole.getRoleName());
        this.update(sysRoleDb);
      }
    }
    if(isNew){//如果是新插入的对象
      sysRole.setCreateTime(new Date());
      insert(sysRole);
    }
    menuIdList.forEach(id ->{
      RoleMenu roleMenu = new RoleMenu();
      roleMenu.setMenuId(id);
      roleMenu.setRoleId(sysRole.getRoleId());
      sysRoleMenuMapper.insertUseGeneratedKeys(roleMenu);
    });
    return sysRole;
  }
}
